import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
import { asyncRoutes } from '@/router'

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/') // next()函数中有值时就不会走后置路由守卫,所以要自己停止进度条
      NProgress.done()
    } else {
      // 当userInfo因为刷新消失后,重新获取
      if (!store.getters.userId) {
        // 获取用户所拥有的权限页面
        const { roles } = await store.dispatch('user/getUserInfo')
        // 筛选出当前用户的动态路由
        const arr = asyncRoutes.filter(item => {
          return roles.menus.includes(item.children[0].name)
        })
        // 添加路由到侧边栏
        store.commit('user/setRoutes', arr)
        // 添加动态路由,解决刷新就出现404问题,因为404页面一定要在所有路由最后
        router.addRoutes([...arr, { path: '*', redirect: '/404', hidden: true }])
        // 添加动态路由后需要转发一下,解决动态路由不显示
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
